const { Controller } = require('egg')
const fs = require('fs')

// 阿里云
const OSS = require('ali-oss')

// 华为云
// const ObsClient = require('esdk-obs-nodejs');
// // 创建ObsClient实例
// const obsClient = new ObsClient({
//     access_key_id: 'PA4LIQPFXPMNRBSQVZO7',
//     secret_access_key: 'dzvEUrBK9hJBzsVG8NS5UIgEJxGeFVAljAXdWife',
//     server : 'https://obs.cn-east-2.myhwclouds.com'
// });

class UploadController extends Controller {
  async upload() {
    const { ctx, config } = this
    const { req } = ctx
    const { query, files } = ctx.request

    const uploadFiles = []

    console.log('upload');

    for (let i = 0; i < files.length; i++) {
      const file = files[i]

      let reutrnData = {
        url: file.url,
        originalName: file.originalname,
        mimeType: file.mimetype,
      }

      // 上传到阿里云
      if ((query.service = 'ali')) {
        console.log("上传到阿里云")
        const client = new OSS(config.aliOSS)

        // 创建可读流
        const stream = fs.createReadStream(file.path)
        let result = await client.putStream(file.key, stream)

        if (result) reutrnData.url = result.url
      }

      // 图片压缩
      // if (file.mimetype.indexOf('image/') != -1) {
      //     if (query.coverWidth)
      //         reutrnData.cover = await getCover(file, query)
      // }

      uploadFiles.push(reutrnData)
    }

    ctx.body = {
      code: 0,
      msg: '上传成功',
      data: uploadFiles,
    }
  }
}

module.exports = UploadController

/**
   * @api {POST} /upload [上传]
   * @apiUse AdminCommon
   * @apiGroup Upload
   * 
   * @apiBody {Array} files 请使用 form-data 格式上传
   *
   * @apiSuccessExample {json} Success-Response:
{
    "code": 0,
    "msg": "上传成功",
    "data": [
        {
            "url": "http://127.0.0.1:7001/uploads/230305/00434414028.jpg",
            "originalName": "2911054692.jpg",
            "mimeType": "image/jpeg"
        },
    ]
}
*/
